import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../core/constants.dart';
import '../../data/models/puzzle_game.dart';
import '../../data/models/puzzle_piece.dart';

class PuzzleBoard extends StatefulWidget {
  final PuzzleGame game;
  final Function(int pieceId)? onPieceClick;
  final Function(int row, int col)? onEmptyGridClick;
  
  const PuzzleBoard({
    super.key,
    required this.game,
    this.onPieceClick,
    this.onEmptyGridClick,
  });
  
  @override
  State<PuzzleBoard> createState() => _PuzzleBoardState();
}

class _PuzzleBoardState extends State<PuzzleBoard> {
  
  @override
  Widget build(BuildContext context) {
    final gridSize = widget.game.difficulty.gridSize;
    final totalPieces = gridSize * gridSize;
    
    debugPrint('界面显示：网格${gridSize}x${gridSize}，总拼图块${totalPieces}个，实际${widget.game.pieces.length}个');
    
    return Column(
      children: [
        // 游戏统计
        _buildGameStats(),
        
        // 目标拼图区域 - 自适应比例
        Expanded(
          flex: 3,
          child: Center(child: _buildAdaptiveTargetGrid()),
        ),
        
        // 散落拼图块区域 - 紧凑布局
        Expanded(
          flex: 2,
          child: _buildCompactScatteredArea(),
        ),
      ],
    );
  }
  
  Widget _buildGameStats() {
    final scatteredCount = widget.game.pieces.where((p) => !p.isInGameArea).length;
    final placedCount = widget.game.pieces.where((p) => p.isInGameArea).length;
    
    return Container(
      padding: const EdgeInsets.all(8),
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(
        '拼图块: ${widget.game.pieces.length}个 | 散落: ${scatteredCount}个 | 已放置: ${placedCount}个',
        style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
      ),
    );
  }
  

// in puzzle_board.dart
/// 自适应比例的目标网格 
Widget _buildAdaptiveTargetGrid() {
  final gridSize = widget.game.difficulty.gridSize;
  final imageAspectRatio = widget.game.imageAspectRatio;

  return LayoutBuilder(
    builder: (context, constraints) {
      final double availableWidth = constraints.maxWidth;
      final double availableHeight = constraints.maxHeight;

      double boardWidth;
      double boardHeight;

      // 根据可用空间和图片比例，计算拼图板的最终尺寸
      if (availableWidth / availableHeight > imageAspectRatio) {
        // 空间比较宽，以高度为基准
        boardHeight = availableHeight;
        boardWidth = boardHeight * imageAspectRatio;
      } else {
        // 空间比较高，以宽度为基准
        boardWidth = availableWidth;
        boardHeight = boardWidth / imageAspectRatio;
      }
      
      // 单个拼图块在UI上的尺寸
      final pieceUIWidth = boardWidth / gridSize;
      final pieceUIHeight = boardHeight / gridSize;

      return Container(
        width: boardWidth,
        height: boardHeight,
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Colors.grey.shade400, width: 2),
        ),
        child: GridView.builder(
          physics: const NeverScrollableScrollPhysics(),
          padding: const EdgeInsets.all(1),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: gridSize,
            crossAxisSpacing: 1,
            mainAxisSpacing: 1,
            childAspectRatio: imageAspectRatio, // 确保网格单元格和图片比例一致
          ),
          itemCount: gridSize * gridSize,
          itemBuilder: (context, index) {
            final row = index ~/ gridSize;
            final col = index % gridSize;
            return _buildTargetSlot(row, col, pieceUIWidth, pieceUIHeight);
          },
        ),
      );
    },
  );
}

  
  /// 构建目标槽位
  Widget _buildTargetSlot(int row, int col, double slotWidth, double slotHeight) {
    final piece = widget.game.pieces.where(
      (p) => p.currentRow == row && p.currentCol == col,
    ).firstOrNull;
    
    final isEmpty = piece == null;
    
    return GestureDetector(
      onTap: () {
        if (isEmpty) {
          widget.onEmptyGridClick?.call(row, col);
        } else {
          widget.onPieceClick?.call(piece!.id);
        }
      },
      child: Container(
        decoration: BoxDecoration(
          color: isEmpty ? Colors.white.withValues(alpha: 0.5) : Colors.transparent,
          border: Border.all(
            color: piece?.isSelected == true ? Colors.blue : Colors.grey.shade300,
            width: piece?.isSelected == true ? 3 : 1,
          ),
          borderRadius: BorderRadius.circular(2),
        ),
        child: isEmpty 
          ? const Icon(Icons.add, color: Colors.grey, size: 16)
          : _buildCorrectPieceImage(piece!, slotWidth, slotHeight),
      ),
    );
  }
  
/// 构建正确的拼图块图片 (终极简化版)
Widget _buildCorrectPieceImage(PuzzlePiece piece, double pieceUIWidth, double pieceUIHeight) {
  // 直接使用 RawImage 来显示 piece 自带的 ui.Image
  return RawImage(
    image: piece.image,
    fit: BoxFit.fill, // 填满给定的UI空间
  );
}






/// 紧凑的散落区域 (最终健壮版：使用 mainAxisExtent)
Widget _buildCompactScatteredArea() {
  final scatteredPieces = widget.game.pieces
      .where((p) => !p.isInGameArea)
      .toList();
  
  if (scatteredPieces.isEmpty) {
    return const Center(child: Text('所有拼图块已放置完成！'));
  }
  
  int targetRows;
  if (scatteredPieces.length <= 12) {
    targetRows = 1;
  } else if (scatteredPieces.length <= 36) {
    targetRows = 2;
  } else {
    targetRows = 3;
  }
  
  const double spacing = 8.0;
  final imageAspectRatio = widget.game.imageAspectRatio;

  return Container(
    margin: const EdgeInsets.fromLTRB(16, 8, 16, 16),
    padding: const EdgeInsets.all(12),
    decoration: BoxDecoration(
      color: Colors.grey.shade50,
      borderRadius: BorderRadius.circular(8),
      border: Border.all(color: Colors.grey.shade300),
    ),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '待拼图块 (${scatteredPieces.length}个)',
          style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 14),
        ),
        const SizedBox(height: 8),
        Expanded(
          child: LayoutBuilder(
            builder: (context, constraints) {
              final double availableHeight = constraints.maxHeight;
              final double pieceUIHeight = (availableHeight - (targetRows - 1) * spacing) / targetRows;

              if (pieceUIHeight <= 0) {
                return const SizedBox.shrink();
              }
              
              // 关键修复：根据高度和比例，精确计算出每个拼图块的宽度
              final double pieceUIWidth = pieceUIHeight * imageAspectRatio;
              
              return GridView.builder(
                scrollDirection: Axis.horizontal,
                padding: EdgeInsets.zero,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: targetRows,
                  mainAxisSpacing: spacing,
                  crossAxisSpacing: spacing,
                  // 关键修复：不再使用 childAspectRatio，而是直接指定主轴尺寸（宽度）
                  mainAxisExtent: pieceUIWidth,
                ),
                itemCount: scatteredPieces.length,
                itemBuilder: (context, index) {
                  return _buildCompactScatteredPiece(scatteredPieces[index]);
                },
              );
            },
          ),
        ),
      ],
    ),
  );
}
  


/// 构建紧凑的散落拼图块 (简化版)
Widget _buildCompactScatteredPiece(PuzzlePiece piece) {
  return GestureDetector(
    onTap: () => widget.onPieceClick?.call(piece.id),
    child: Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: piece.isSelected ? Colors.blue : Colors.grey.shade400,
          width: piece.isSelected ? 2.5 : 1,
        ),
        borderRadius: BorderRadius.circular(4),
        // 如果选中，给一个淡淡的蓝色背景作为高亮提示
        color: piece.isSelected ? Colors.blue.withOpacity(0.2) : Colors.transparent, 
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(3),
        // 直接用 RawImage 显示已经切好的图
        child: RawImage(
          image: piece.image,
          fit: BoxFit.cover, // cover 能够填满容器
        ),
      ),
    ),
  );
}

  

  
  
  /// 计算最佳列数
  int _calculateOptimalColumns(int pieceCount) {
    if (pieceCount <= 9) return 3;
    if (pieceCount <= 16) return 4;
    if (pieceCount <= 25) return 5;
    return 6;
  }
  
  /// 计算最佳拼图块大小
  double _calculateOptimalPieceSize(int columns) {
    // 根据可用宽度和列数计算
    final availableWidth = MediaQuery.of(context).size.width - 64; // 减去边距
    final pieceSize = (availableWidth / columns) - 12; // 减去间距
    return math.min(pieceSize, 80.0); // 最大80像素
  }
}
